package com.bodacn.keypoint;

import android.app.Activity;
import android.app.DatePickerDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.text.format.DateFormat;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import org.json.JSONArray;
import org.json.JSONException;
import org.ksoap2.SoapEnvelope;
import org.ksoap2.SoapFault;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpResponseException;
import org.ksoap2.transport.HttpTransportSE;
import org.xmlpull.v1.XmlPullParserException;

import java.io.IOException;
import java.sql.SQLOutput;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Timer;
import java.util.TimerTask;

public class DispatchActivity extends Activity implements View.OnClickListener {
    Button btn_Return,btn_refresh;
    CheckBox chk_viewAllAcc,chk_viewAllOutNeed;
    String curLoginUserNo,curLoginUser,curServiceUrl="",curServiceDir="",curDepartNo,curDepart,CPUID,BoardNo="";
    ListView callListView,accListView,cutListView;
    EditText edt_viewDate;
    //用于与主Activity通讯;
    private JSONArray cutJson,accJson,callJson;//用于存储WebService返回的结果;
    //初始化定时器;
    private Timer timer;
    private TimerTask timetask;
    private static int runCount=0;//计数器，超过一定的次数，就刷新数据;
    //媒体播放文件
    private static MediaPlayer mediaPlayer;
    private boolean firstLoad = false;
    int SwitchCount,SpaceSec;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_dispatch);
        //获取登陆参数
        firstLoad=true;
        Bundle paramBundle = this.getIntent().getExtras();
        curLoginUserNo=paramBundle.getString("LoginUserNo");
        curLoginUser=paramBundle.getString("LoginUser");
        curDepartNo=paramBundle.getString("CurDepartNO");
        curDepart=paramBundle.getString("CurDepart");
        curServiceUrl=paramBundle.getString("ServiceUrl");
        curServiceDir=paramBundle.getString("ServiceDir");
        SpaceSec=paramBundle.getInt("SpaceSec");
        SwitchCount=paramBundle.getInt("SwitchCount");
        CPUID=paramBundle.getString("CPUID");
        BoardNo=paramBundle.getString("BoardNo");
        System.out.println(paramBundle);
        //初始化界面
        btn_Return=findViewById(R.id.btn_Return);
        btn_Return.setOnClickListener(this);
        btn_refresh=findViewById(R.id.btn_refresh);
        btn_refresh.setOnClickListener(this);
        chk_viewAllAcc=findViewById(R.id.chk_viewAllAcc);
        chk_viewAllOutNeed=findViewById(R.id.chk_viewAllOutNeed);
        callListView=findViewById(R.id.callListView);
        callListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (callJson!=null){
                    if (callJson.length()>position){
                        try {
                            String Department=callJson.getJSONObject(position).getString("Depart");
                            if (chk_viewAllOutNeed.isChecked()) GetCutData("Check",edt_viewDate.getText().toString(),Department);
                            else GetCutData("unCheck",edt_viewDate.getText().toString(),Department);
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        accListView=findViewById(R.id.accListView);
        cutListView=findViewById(R.id.cutListView);
        cutListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (cutJson!=null){
                    if (cutJson.length()>position){
                        try {
                            String dbh=cutJson.getJSONObject(position).getString("DBH");
                            if (chk_viewAllAcc.isChecked()) GetAccData(dbh,"Check",edt_viewDate.getText().toString());
                            else GetAccData(dbh,"unCheck",edt_viewDate.getText().toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        });
        edt_viewDate=findViewById(R.id.edt_viewDate);
        edt_viewDate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                final Calendar calendar = Calendar.getInstance();
                final DatePickerDialog mDialog = new DatePickerDialog(DispatchActivity.this, null, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DAY_OF_MONTH));
                mDialog .setButton(DialogInterface.BUTTON_POSITIVE,getString(R.string.Finish),new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        DatePicker datePicker = mDialog.getDatePicker();
                        int year = datePicker.getYear();
                        int month = datePicker.getMonth();
                        int day = datePicker.getDayOfMonth();
                        calendar.set(year,month,day);
                        edt_viewDate.setText(DateFormat.format("yyyy-MM-dd", calendar));
                    }
                });
                mDialog.setButton(DialogInterface.BUTTON_NEGATIVE,getString(R.string.Cancel),new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        System.out.println("cancel~~cancel~~");
                    }
                });
                mDialog.setTitle(getString(R.string.PleaseSelectQueryDate));
                mDialog.show();

            }
        });

        edt_viewDate.setOnFocusChangeListener(new View.OnFocusChangeListener() {
            @Override
            public void onFocusChange(View v, boolean hasFocus) {
                Log.d("edit_startDate","onFocusChange");
                if (hasFocus == true) {
                    hideIM(v);
                }
            }
        });
        //置日期初始值;
        Date curDate = new Date(System.currentTimeMillis());
        String StartDateStr=(String) DateFormat.format("yyyy-MM-dd", new Date(curDate.getTime()));
        edt_viewDate.setText(StartDateStr);

    }


    // 隐藏手机键盘
    private void hideIM(View edt) {
        try {
            InputMethodManager im = (InputMethodManager) getApplicationContext().getSystemService(Activity.INPUT_METHOD_SERVICE);
            IBinder windowToken = edt.getWindowToken();
            if (windowToken != null) {
                im.hideSoftInputFromWindow(windowToken, 0);
            }
        } catch (Exception e) {

        }
    }
    @Override
    public void onClick(View v) {
        switch (v.getId())
        {
            case R.id.btn_Return:
                finish();
                break;
            case R.id.btn_refresh:
                if (chk_viewAllOutNeed.isChecked()) GetCutData("Check",edt_viewDate.getText().toString(),"");
                else GetCutData("unCheck",edt_viewDate.getText().toString(),"");
            default:
                break;
        }
    }

    //获取裁片需求;
    private void GetCutData(String paramCheck,String paramViewDate,String paramDepartment) {
        try {
            cutJson=new JSONArray("[]");
            //如果是表格内容，则显示表格格中;
            final CutListAdapter myAdapter = new CutListAdapter(getApplicationContext());
            cutListView.setAdapter(myAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //置值
        String tmpServiceUrl=curServiceUrl;
        //执行SQL过程
        String methodName="ExecSql";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap1=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap1.put("SqlComm", "Exec LookBoardTV_Storage @BoardNo=\'" + BoardNo + "\',@OperType=\'DispatchCUT\',@Check=\'"+paramCheck+"\',@ViewDate=\'"+paramViewDate+"\',@Department=\'"+paramDepartment+"\'");
        //调用WebService过程并处理界面更新;
        ReadSQLData(tmpServiceUrl, methodName, paramMap1);
    }

    //获取辅料需求;
    private void GetAccData(String paramDBH,String paramCheck,String paramViewDate) {
        try {
            accJson=new JSONArray("[]");
            //如果是表格内容，则显示表格格中;
            final AccListAdapter myAdapter = new AccListAdapter(getApplicationContext());
            accListView.setAdapter(myAdapter);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //置值
        String tmpServiceUrl=curServiceUrl;
        //执行SQL过程
        String methodName="ExecSql";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap1=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap1.put("SqlComm", "Exec LookBoardTV_Storage @BoardNo=\'" + BoardNo + "\',@OperType=\'DispatchACC\',@DBH=\'"+paramDBH+"\',@Check=\'"+paramCheck+"\',@ViewDate=\'"+paramViewDate+"\'");
        //调用WebService过程并处理界面更新;
        ReadSQLData(tmpServiceUrl, methodName, paramMap1);
    }

    //获取呼叫需求;
    private void GetCallData() {
        try {
            callJson=new JSONArray("[]");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        //置值
        String tmpServiceUrl=curServiceUrl;
        //执行SQL过程
        String methodName="ExecSql";
        //通过哈希数组来传递参数;
        Map<String,Object> paramMap1=new HashMap<String,Object>();
        //可传递多个参数  paramMap.put(paramName, paramValue);
        paramMap1.put("SqlComm", "Exec LookBoardTV_Storage @BoardNo=\'" + BoardNo + "\',@OperType=\'DispatchCALL\'");
        //调用WebService过程并处理界面更新;
        ReadSQLData(tmpServiceUrl, methodName, paramMap1);
    }


    public void ReadSQLData(String serviceUrl,String methodName,Map<String,Object> paramMap) {
        //组织参数传到匿名类中;
        Map<String,Object> params=new HashMap<String,Object>();
        params.put("serviceUrl",serviceUrl);
        params.put("methodName",methodName);
        params.put("paramMap",paramMap);
        System.out.println("ReadSQL:"+paramMap);
        //创建匿名类用于WebService调用;
        new AsyncTask<Map<String,Object>,Void,String>()
        {
            @Override
            protected String doInBackground(Map<String, Object>... params) {
                String serviceUrl= (String) params[0].get("serviceUrl");
                System.out.println(serviceUrl);
                String methodName= (String) params[0].get("methodName");
                try {
                    //置参数给对象
                    String namespace="http://tempuri.org/";
                    SoapObject soapObject=new SoapObject(namespace, methodName);
                    SoapSerializationEnvelope envelope=new SoapSerializationEnvelope(SoapEnvelope.VER11);
                    //遍列Map数组加参数
                    Map<String,Object> paramMap= (Map<String,Object>) params[0].get("paramMap");
                    Iterator iterator = paramMap.keySet().iterator();
                    while (iterator.hasNext())
                    {
                        String paramkey = (String) iterator.next();
                        String paramvalue = (String) paramMap.get(paramkey);
                        soapObject.addProperty(paramkey,paramvalue);//带参数的方法调用，若调用无参数的，则无需此句
                    }
                    //准备执行WebService
                    envelope.dotNet=true;
                    envelope.setOutputSoapObject(soapObject);
                    HttpTransportSE httpTranstation=new HttpTransportSE(serviceUrl);

                    //执行调用WebService;
                    httpTranstation.call(namespace+methodName, envelope);
                    //获取返回会值;
                    Object result=envelope.getResponse();
                    //将获取的返回值转成字符串
                    String resultstr=(String) result.toString();
                    System.out.println(resultstr);
                    //字符串数据直接返回，由回调函数OnPostExecute中进行UI刷新显示;
                    return resultstr;
                } catch (HttpResponseException e) {
                    e.printStackTrace();
                } catch (SoapFault soapFault) {
                    soapFault.printStackTrace();
                } catch (XmlPullParserException e) {
                    e.printStackTrace();
                } catch (IOException e) {
                    e.printStackTrace();
                }
                return null;
            }

            @Override
            protected void onPostExecute(String s) {
                super.onPostExecute(s);
                if (s==null) return;
                //这部分主要用于UI更新;
                try {
                    //字符串转JSON序列;
                    /*
                    //如果返回的格式中有键值[data:{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]
                    JSONObject obj = new JSONObject(result.toString());
                    JSONArray jsonArray = (JSONArray)obj.getJSONArray("data");
                    */
                    //返回的格式如[{name:aa arg:12}{name:aa arg:12}{name:aa arg:12}]则直接转换即可
                    System.out.println("接收到的内容:"+s);
                    JSONArray jsonArray = new JSONArray(s);
                    //往界面转数据;
                    if (jsonArray.length()>0) {
                        if (jsonArray.optJSONObject(0).has("OperType")==true) {
                            //呼叫信息及库存警告
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("DispatchCUT")==true)
                            {
                                //往界面转数据;
                                cutJson=jsonArray;
                                System.out.println("准备显示到cutListView");
                                //如果是标题刷来的值，则显示到标题中;
                                //如果是表格内容，则显示表格格中;
                                final CutListAdapter myAdapter = new CutListAdapter(getApplicationContext());
                                cutListView.setAdapter(myAdapter);
                                System.out.println("显示完成");
                            }
                            //呼叫信息及库存警告
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("DispatchACC")==true)
                            {
                                //往界面转数据;
                                accJson=jsonArray;
                                System.out.println("准备显示到accListView");
                                //如果是标题刷来的值，则显示到标题中;
                                //如果是表格内容，则显示表格格中;
                                final AccListAdapter myAdapter = new AccListAdapter(getApplicationContext());
                                accListView.setAdapter(myAdapter);
                                System.out.println("显示完成");
                            }
                            //呼叫信息及库存警告
                            if (jsonArray.optJSONObject(0).getString("OperType").equals("DispatchCALL")==true)
                            {
                                //往界面转数据;
                                callJson=jsonArray;
                                System.out.println("准备显示到callListView");
                                //如果是标题刷来的值，则显示到标题中;
                                //如果是表格内容，则显示表格格中;
                                final CallListAdapter myAdapter = new CallListAdapter(getApplicationContext());
                                callListView.setAdapter(myAdapter);
                                System.out.println("显示完成");
                            }
                        }
                    } else
                    {
                        //判断是否要清空呼叫;
                        if (callJson!=null)
                        {
                            if (callJson.length()==0) {
                                //如果是表格内容，则显示表格格中;
                                final CallListAdapter myAdapter = new CallListAdapter(getApplicationContext());
                                callListView.setAdapter(myAdapter);
                            }
                        }
                    }
                    //pageInfoText.setText("["+(curPage+1)+"/"+pageCount+"]");
                    System.out.println("准备显示到ListView");
                } catch (JSONException e) {
                    e.printStackTrace();

                }
            }
        }.execute(params);

    }

    public  String TrnasValue(String params)
    {
        if (params.toUpperCase().equals("NULL")||params.equals("0")||params.equals("0.0"))
            return "";
        else return params;
    }
    //合约表格适配器;
    public final class CutListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public CutListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return cutJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                if (position<cutJson.length())
                    return cutJson.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.listitem_dispatch_cut, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(42)));
            //转换分页码;
            TextView tv;
            int curPosition=position;
            String tmpValue="";
            int color = getResources().getColor(R.color.text_black);
            try {
                Log.d("msg", "getView()----------------------------------------------------->" + position);
                if (cutJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = cutJson.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                    if (tmpValue.equals("0"))
                        color = getResources().getColor(R.color.text_black);
                }
                tv = convertView.findViewById(R.id.tv_grid_Depart);
                if (cutJson.optJSONObject(curPosition).has("Depart") == true)
                    tv.setText(cutJson.optJSONObject(curPosition).getString("Depart").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_CarNo);
                if (cutJson.optJSONObject(curPosition).has("CarNo") == true)
                    tv.setText(cutJson.optJSONObject(curPosition).getString("CarNo").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_StyleNo);
                if (cutJson.optJSONObject(curPosition).has("StyleNo") == true)
                    tv.setText(cutJson.optJSONObject(curPosition).getString("StyleNo").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_OrderNo);
                if (cutJson.optJSONObject(curPosition).has("OrderNo") == true)
                    tv.setText(TrnasValue(cutJson.optJSONObject(curPosition).getString("OrderNo").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_StyleSort);
                if (cutJson.optJSONObject(curPosition).has("StyleSort") == true)
                    tv.setText(TrnasValue(cutJson.optJSONObject(curPosition).getString("StyleSort").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_DBH);
                if (cutJson.optJSONObject(curPosition).has("DBH") == true)
                    tv.setText(TrnasValue(cutJson.optJSONObject(curPosition).getString("DBH").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_ColorNo);
                if (cutJson.optJSONObject(curPosition).has("ColorNo") == true)
                    tv.setText(TrnasValue(cutJson.optJSONObject(curPosition).getString("ColorNo").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_Color);
                if (cutJson.optJSONObject(curPosition).has("Color") == true)
                    tv.setText(cutJson.optJSONObject(curPosition).getString("Color").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_PSXX);
                if (cutJson.optJSONObject(curPosition).has("PSXX") == true)
                    tv.setText(cutJson.optJSONObject(curPosition).getString("PSXX").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_Size);
                if (cutJson.optJSONObject(curPosition).has("Size") == true)
                    tv.setText(cutJson.optJSONObject(curPosition).getString("Size").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_NeedNum);
                if (cutJson.optJSONObject(curPosition).has("NeedNum") == true)
                    tv.setText(cutJson.optJSONObject(curPosition).getString("NeedNum").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_NeedPack);
                if (cutJson.optJSONObject(curPosition).has("NeedPack") == true)
                    tv.setText(cutJson.optJSONObject(curPosition).getString("NeedPack").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_ReadyNum);
                if (cutJson.optJSONObject(curPosition).has("ReadyNum") == true)
                    tv.setText(cutJson.optJSONObject(curPosition).getString("ReadyNum").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_HouseName);
                if (cutJson.optJSONObject(curPosition).has("HouseName") == true)
                    tv.setText(cutJson.optJSONObject(curPosition).getString("HouseName").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_BoxNo);
                if (cutJson.optJSONObject(curPosition).has("BoxNo") == true)
                    tv.setText(cutJson.optJSONObject(curPosition).getString("BoxNo").toString());
                tv.setTextColor(color);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            return convertView;
        }
    }

    //合约表格适配器;
    public final class AccListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public AccListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return accJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                if (position<accJson.length())
                    return accJson.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.listitem_dispatch_acc, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(42)));
            //转换分页码;
            TextView tv;
            int curPosition=position;
            String tmpValue="";
            int color = getResources().getColor(R.color.text_black);
            try {
                Log.d("msg", "getView()----------------------------------------------------->" + position);
                if (accJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = accJson.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                    if (tmpValue.equals("0"))
                        color = getResources().getColor(R.color.text_black);
                }
                tv = convertView.findViewById(R.id.tv_grid_Depart);
                if (accJson.optJSONObject(curPosition).has("Depart") == true)
                    tv.setText(accJson.optJSONObject(curPosition).getString("Depart").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_CarNo);
                if (accJson.optJSONObject(curPosition).has("CarNo") == true)
                    tv.setText(accJson.optJSONObject(curPosition).getString("CarNo").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_StyleNo);
                if (accJson.optJSONObject(curPosition).has("StyleNo") == true)
                    tv.setText(accJson.optJSONObject(curPosition).getString("StyleNo").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_OrderNo);
                if (accJson.optJSONObject(curPosition).has("OrderNo") == true)
                    tv.setText(TrnasValue(accJson.optJSONObject(curPosition).getString("OrderNo").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_StyleSort);
                if (accJson.optJSONObject(curPosition).has("StyleSort") == true)
                    tv.setText(TrnasValue(accJson.optJSONObject(curPosition).getString("StyleSort").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_DBH);
                if (accJson.optJSONObject(curPosition).has("DBH") == true)
                    tv.setText(TrnasValue(accJson.optJSONObject(curPosition).getString("DBH").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_ColorNo);
                if (accJson.optJSONObject(curPosition).has("ColorNo") == true)
                    tv.setText(TrnasValue(accJson.optJSONObject(curPosition).getString("ColorNo").toString()));
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_Color);
                if (accJson.optJSONObject(curPosition).has("Color") == true)
                    tv.setText(accJson.optJSONObject(curPosition).getString("Color").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_PSXX);
                if (accJson.optJSONObject(curPosition).has("PSXX") == true)
                    tv.setText(accJson.optJSONObject(curPosition).getString("PSXX").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_Size);
                if (accJson.optJSONObject(curPosition).has("Size") == true)
                    tv.setText(accJson.optJSONObject(curPosition).getString("Size").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_NeedNum);
                if (accJson.optJSONObject(curPosition).has("NeedNum") == true)
                    tv.setText(accJson.optJSONObject(curPosition).getString("NeedNum").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_NeedPack);
                if (accJson.optJSONObject(curPosition).has("NeedPack") == true)
                    tv.setText(accJson.optJSONObject(curPosition).getString("NeedPack").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_ReadyNum);
                if (accJson.optJSONObject(curPosition).has("ReadyNum") == true)
                    tv.setText(accJson.optJSONObject(curPosition).getString("ReadyNum").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_HouseName);
                if (accJson.optJSONObject(curPosition).has("HouseName") == true)
                    tv.setText(accJson.optJSONObject(curPosition).getString("HouseName").toString());
                tv.setTextColor(color);
                tv = convertView.findViewById(R.id.tv_grid_BoxNo);
                if (accJson.optJSONObject(curPosition).has("BoxNo") == true)
                    tv.setText(accJson.optJSONObject(curPosition).getString("BoxNo").toString());
                tv.setTextColor(color);
            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            return convertView;
        }
    }

    //合约表格适配器;
    public final class CallListAdapter extends BaseAdapter {
        private LayoutInflater inflater;
        public CallListAdapter(Context context) {
            inflater = (LayoutInflater) context
                    .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        @Override
        public int getCount() {
            return callJson.length();
        }

        @Override
        public Object getItem(int position) {
            try {
                if (position<callJson.length())
                    return callJson.getJSONArray(position);
                else
                    return null;
            } catch (JSONException e)
            {
                e.printStackTrace();
                System.out.println("getItem取JSON数据出错!");
                return  null;
            }
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            if (convertView == null) convertView = inflater.inflate(R.layout.listitem_dispatch_call, null, false);
            int pullVatListWidth=parent.getWidth();
            convertView.setLayoutParams(new ListView.LayoutParams((int)pullVatListWidth,(int)(42)));
            //转换分页码;
            TextView tv;
            int curPosition=position;
            String tmpValue="";
            int color = getResources().getColor(R.color.text_black);
            try {
                Log.d("msg", "getView()----------------------------------------------------->" + position);
                if (callJson.optJSONObject(position).has("ConColor") == true) {
                    tmpValue = callJson.optJSONObject(position).getString("ConColor").toString();
                    if (tmpValue.equals("1"))
                        color = getResources().getColor(R.color.text_blue);
                    if (tmpValue.equals("2"))
                        color = getResources().getColor(R.color.text_red);
                    if (tmpValue.equals("3"))
                        color = getResources().getColor(R.color.text_gray);
                    if (tmpValue.equals("0"))
                        color = getResources().getColor(R.color.text_black);
                }
                tv = convertView.findViewById(R.id.tv_grid_Depart);
                if (callJson.optJSONObject(curPosition).has("Depart") == true)
                    tv.setText(callJson.optJSONObject(curPosition).getString("Depart").toString());
                tv.setBackgroundColor(color);
                tv = convertView.findViewById(R.id.tv_grid_State);
                if (callJson.optJSONObject(curPosition).has("State") == true)
                    tv.setText(callJson.optJSONObject(curPosition).getString("State").toString());
                tv.setBackgroundColor(color);

            } catch (JSONException e) {
                e.printStackTrace();
                System.out.println(e.getMessage());
            }
            return convertView;
        }
    }

    //启动定时器;
    private void startTimer(){
        //启动计时任务;
        System.out.println("TwoFragment----startTimer");
        //得到Activity的Handler,用于发消息给主Activity;
        int spaceMiSec=SpaceSec*1000;
        System.out.println("refreshSpaceSec:"+spaceMiSec);
        if (timer == null) {
            timer = new Timer();
        }
        //定时任务;
        if (timetask == null) {
            timetask = new TimerTask() {
                @Override
                public void run() {
                    //也可发消息，由Handler负责统一调度执行;
                    Message message = new Message();
                    message.what = 1;
                    handler.sendMessage(message);
                }
            };
            timer.schedule(timetask, 1000, spaceMiSec);
        }
        System.out.println("startTimer Two ---------------------------------Start");
    }


    //停止计时器;
    private void stopTimer(){
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (timetask != null) {
            timetask.cancel();
            timetask = null;
        }
        System.out.println("startTimer Two---------------------------------Over");
    }

    //通过消息来执行处理类程序,不更新UI则不一定需要通过这个;
    final Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            // TODO Auto-generated method stub
            // 根据消息ID来判断要做的事情
            int msgId = msg.what;
            switch (msgId) {
                case 1:
                    if (firstLoad==true) {
                        firstLoad=false;
                        GetCallData();
                        GetCutData("unCheck",edt_viewDate.getText().toString(),"");
                    } else
                    {
                        System.out.println("重新获取呼叫....");
                        GetCallData();
                    }
                    break;
                default:
                    break;
            }
        }
    };
    @Override
    public void onDestroy() {
        super.onDestroy();
        stopTimer();
        stopMusic();
    }

    @Override
    public void onStart() {
        super.onStart();
        startTimer();
        System.out.println("PullActivity----onStart");
    }

    @Override
    public void onPause() {
        super.onPause();
        stopTimer();
        stopMusic();
        System.out.println("HouseActivity----onPause");
    }

    /**
     * 创建网络mp3
     * @return
     */
    public MediaPlayer createNetMp3(){
        String url=curServiceDir+"/warn.mp3";
        System.out.println("音乐文件地址："+url);
        MediaPlayer mp=new MediaPlayer();
        try {
            mp.setDataSource(url);
        } catch (IllegalArgumentException e) {
            return null;
        } catch (IllegalStateException e) {
            return null;
        } catch (IOException e) {
            return null;
        }
        return mp;
    }

    //插放音乐;
    private void playMusic(){
        try {
            if(mediaPlayer==null) {
                mediaPlayer = createNetMp3();
                mediaPlayer.setLooping(false);
                //在播放音频资源之前，必须调用Prepare方法完成些准备工作
                mediaPlayer.prepare();
            }
            if(mediaPlayer!=null) {
                if (mediaPlayer.isPlaying()==false) mediaPlayer.start();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //停止播放音乐
    private  void  stopMusic(){
        if(mediaPlayer!=null){
            mediaPlayer.stop();//停止播放
            mediaPlayer.release();//释放资源
            mediaPlayer=null;
        }
    }
}
